var tableArray = new Array();
layui.use(['layer', 'form', 'element', 'table'], function() {
	var layer = layui.layer,
		form = layui.form,
		element = layui.element,
		table = layui.table;

	if(GetQueryString("urltype")) {
		//	是否显示确认选择按钮
		$("#yeschoice").show();
	} else {
		$("#yeschoice").hide();
	}

	cMListFn(1, 100, '{"Sorting":"updateTime" }');

	function cMListFn(curr, limit, needjson) {
		//商品查询
		AjaxPostFn('system/commodity/select?page=' + curr + '&pagesize=' + limit, needjson, function(jsonData) {
			tableArray = [];
			$.each(jsonData.pageInfo.list, function(i, obj) {
				tableArray.push({
					"id": obj.id,
					"operation": '<a class="layui-btn " lay-event="updataFile" >上传主图</a><a class="layui-btn layui-btn-normal " lay-event="saleAdd" >加入销售</a>',
//					<a class="layui-btn layui-btn-danger " lay-event="delthis" >删除</a>
					"barCode": obj.barCode,
					"commodityBrand": obj.commodityBrand,
					"commodityName": obj.commodityName,
					"commodityModel": obj.commodityModel,
					"commodityOrigin": obj.commodityOrigin,
					"commodityWeigh": obj.commodityWeigh,
					"commodityUnit": obj.commodityUnit,
					"commoditySet": obj.commoditySet,
					"commodityPhoto": obj.commodityPhoto,
					"commodityApply": obj.commodityApply,
					"commoditySummary": obj.commoditySummary,
					"homePhoto1": "<img src='" + IMGUrl + '' + obj.homePhoto + "' alt='分类主图' class='classifyimg'>",
					"homePhoto2": obj.homePhoto,
					"createTime": getMyDate(obj.createTime),
					"createId": obj.createId,
					"updateTime": getMyDate(obj.updateTime),
					"updateId": obj.updateId,
					"merchantNumber": obj.merchantNumber,
					"commodityDescription": obj.commodityDescription
				});
			})

			//展示已知数据
			table.render({
				elem: '#cMtable',
				cols: [
					[ //标题栏

						{
							type: 'checkbox',
							fixed: 'left'
						}, {
							type: 'numbers',
							fixed: 'left',
							title: '行号'
						}, {
							field: 'id',
							minWidth: '0%',
							width: '0%',
							type: 'space',
							style: 'display:none'
						}, {
							field: 'operation',
							width: 280,
							title: '操作',
							fixed: 'left'
						}, {
							field: 'barCode',
							width: 180,
							title: '条码'
						}, {
							field: 'commodityBrand',
							width: 150,
							title: '商品品牌' + modDot,
							edit: 'text'
						}, {
							field: 'commodityName',
							width: 200,
							title: '商品名称' + modDot,
							edit: 'text'
						}, {
							field: 'homePhoto1',
							width: 100,
							title: '主图'
						}, {
							field: 'commodityModel',
							width: 100,
							title: '型号' + modDot,
							edit: 'text'
						}, {
							field: 'commodityOrigin',
							width: 100,
							title: '产地' + modDot,
							edit: 'text'
						}, {
							field: 'commodityWeigh',
							width: 100,
							title: '重量' + modDot,
							edit: 'text'
						}, {
							field: 'commodityUnit',
							width: 100,
							title: '单位' + modDot,
							edit: 'text'
						}, {
							field: 'commoditySet',
							width: 100,
							title: '规格' + modDot,
							edit: 'text'
						}, {
							field: 'commodityApply',
							width: 150,
							title: '适用范围' + modDot,
							edit: 'text'
						}, {
							field: 'commoditySummary',
							width: 100,
							title: '概述' + modDot,
							event: 'setIntroduce'
						}, {
							field: 'merchantNumber',
							width: 110,
							title: '店家编号'
						}, {
							field: 'createTime',
							width: 200,
							title: '新增时间'
						}, {
							field: 'createId',
							width: 100,
							title: '新增人'
						}, {
							field: 'updateTime',
							width: 200,
							title: '修改时间'
						}, {
							field: 'updateId',
							width: 110,
							title: '最后修改人'
						},
					]
				],
				data: tableArray,
				size: 'lg',
				even: true,
				page: true, //是否显示分页

				height: 'full-300',
				done: function() {
					//图片点击放大
					TopimgFn();
				}
			}); //数据渲染结束
		})
	} //cMListFn函数结束

	//监听单元格编辑
	table.on('edit(table100)', function(obj) {
		var value = obj.value //得到修改后的值
			,
			data = obj.data //得到所在行所有键值
			,
			field = obj.field; //得到字段
		data.updateTime = getnowhour();
		data.updateId = '1';

		AjaxPostFn('system/commodity/update', JSON.stringify(data), function(jsonData) {
			if(jsonData.htmlState.status == 200) {
				layer.msg("修改成功");
			}
		})

	});

	//监听表格内的按钮
	table.on('tool(table100)', function(obj) {
		var data = obj.data;
		if(obj.event === 'updataFile') {
			//上传主图
			layer.open({
				title: '上传图片',
				area: ['390px', '260px'],
				shade: 0,
				maxmin: true,
				btn: ['上传'],
				content: ' <form action="nickName" method="post"  enctype="multipart/form-data" target="framFile"  class="updataform"  >  <input type="file" name="files"  multiple="true" class="file_upload" />  </form>',
				yes: function() {
					thisid = data;
					$(".updataform").submit();
				},
				success: function(layero) {}
			});
			var thisid = 1;
			var framFile = document.getElementById('framFile');
			var imgdata;
			framFile.onload = function() {
				imgdata = framFile.contentWindow.document.getElementsByTagName("pre")[0].innerHTML;
				imgdata = JSON.parse(imgdata).dataResultObj[0];
				AjaxPostFn('system/commodity/update', "{'id':'" + thisid.id + "','homePhoto':'" + imgdata + "','merchantNumber':'" + thisid.merchantNumber + "','merchantNumber':'" + data.merchantNumber + ", 'updateId':'1','updateTime':'" + getnowhour() + "'}", function(jsonData) {
					if(jsonData.htmlState.status == 200) {
						layer.msg("修改成功");
						layer.closeAll();
						location.reload();
					}

				});
			}
		} else if(obj.event === 'delthis') {
			//删除
			layer.confirm('是否删除该条信息', function(index) {
				AjaxPostFn('system/commodity/deletecommodity', "{'id':'" + data.id + "'}", function(jsonData) {
					if(jsonData.htmlState.status == 200) {
						layer.msg("删除成功");
					} else {
						layer.msg(jsonData.htmlState.message);
					}
				});
				AjaxPostFn('system/repository/delete', "{'id':'" + data.id + "'}", function(jsonData) {
					//删除相应的库存
				});
				AjaxPostFn('system/commoditdetails/updatebyid', "{'id':'" + data.id + "','shelfState':'0'}", function(jsonData) {
					//下架该商品
				})
				obj.del();
				layer.close(index);
			});
		} else if(obj.event === 'setIntroduce') {
			//修改概述
			layer.prompt({
				formType: 2,
				title: '修改  [' + data.commodityName + '] 的概述',
				value: data.commoditySummary
			}, function(value, index) {
				layer.close(index);
				AjaxPostFn('system/commodity/update', "{'id':'" + data.id + "','commoditySummary':'" + value + "','merchantNumber':'" + data.merchantNumber + ", 'updateId':'1','updateTime':'" + getnowhour() + "'}", function(jsonData) {
					if(jsonData.htmlState.status == 200) {
						layer.msg("修改成功");
					}
				})
				obj.update({
					commoditySummary: value
				});
			});
		} else if(obj.event === 'insertAdd') {
			//							加入库存
			layer.open({
				type: 1,
				skin: 'layui-layer-demo', //样式类名
				closeBtn: 0, //不显示关闭按钮
				title: '将' + data.commodityName + '加入库存',
				shadeClose: true, //开启遮罩关闭
				content: $("#ainstBox").html(),
				success: function(res, index) {
					console.log("点击了加入库存窗口");
					$(".yesInsert").click(function() {
						//点击确认入库
						inputisNull("#ainstBoxform input", function() {
							var thisdata = $("#ainstBoxform").serializeJson();
							thisdata.updateId = '';
							thisdata.updateTime = getnowtime();
							thisdata.commodityName = data.commodityName;
							thisdata.barCode = data.barCode;
							thisdata.createTime = getnowtime();
							thisdata.merchantNumber = data.merchantNumber;
							thisdata.commodityId = data.id;
							AjaxPostFn('system/repository/insert', JSON.stringify(thisdata), function(jsonData) {
								if(jsonData.htmlState.status == 200) {
									layer.msg("增加到库存成功");
									layer.close(index);
								} else {
									layer.msg("请求异常");
								}
							})
						})
					});
					$(".noInsert").click(function() {
						layer.closeAll();
					})
				}
			});

		} else if(obj.event === 'sysInAdd') {
			//加入到采购入库
			var postindata = {
				"batchId": 1,
				"locationId": "0",
				"theNum": 10,
				"merchantNumber": '1',
				"barCode": "BC20180330"
			};
			//加入到采购入库
			AjaxPostFn('system/repository/in/insert', postdata, function(jsonData) {
				if(jsonData.htmlState.status == 200) {
					layer.msg("增加成功");
					layer.closeAll();
				}
			})
		} else if(obj.event === 'saleAdd') {
			//加入到销售商品
			layer.open({
				type: 1,
				skin: 'layui-layer-molv',
				title: '加入到销售商品',
				area: ['100%', '100%'],
				content: $("#addsaleBox").html(),
				skin: 'demo-class',
				btn: ["确认新增", "关闭"],
				maxmin: true,
				yes: function(index, layero) {
					//按钮1的回调
					inputisNull("#saleform input", function() {
						var thisdata = $("#saleform").serializeJson();
						thisdata.mainPhoto = data.homePhoto2;
						thisdata.createDate = getnowhour();
						thisdata.barCode = data.barCode;
						thisdata.introduce = data.commoditySummary
						thisdata.commodityId = data.id;
						var postdata = '{"info":' + JSON.stringify(thisdata) + ',"price":[{"commodityNumber":"' + thisdata.commodityNumber + '","adcode":"100000","presentPrice":"' + thisdata.presentPrice + '","originalPrice":"' + thisdata.originalPrice + '"}]}';

						var Indata = $("#addInform").serializeJson();
						Indata.updateId = '1';
						Indata.updateTime = new Date().getTime();
						Indata.barCode = thisdata.barCode;
						Indata.createTime = new Date().getTime();
						Indata.commodityNumber = thisdata.commodityNumber;
						Indata.merchantNumber = '1';

						//将商品加入销售
						AjaxPostFn('system/commoditdetails/insertinfoprice', postdata, function(jsonData) {
							if(jsonData.htmlState.status == 200) {
								layer.msg("增加成功");
								AjaxPostFn('system/repository/insert', JSON.stringify(Indata), function(jsonData) {
									if(jsonData.htmlState.status == 200) {

										layer.closeAll();
									}
								})
							}
						}, Indata)

					});
				},
				success: function() {
					//下拉选择重新赋值
					AjaxPostFn('system/catalog/selectallcatalog', "{}", function(jsonData) {
							$.each(jsonData.dataResultList, function(i, obj) {
								$("#Pidselect").append("<option value='" + obj.catalogId + "'>" + obj.nodeName + "</option>");
							})
							form.render();
						})
						//form初始化
					form.render();
//					$("#commodityNumber").val(new Date().getTime())
				}
			})
		}
	});

	//处理弹框的事件
	$('.openwinbtn').on('click', function() {
		var othis = $(this),
			method = othis.data('method');
		active[method] ? active[method].call(this, othis) : '';
	});

	var active = {
			//         弹出框事件
			addmang: function() {
				layer.open({
					type: 1,
					maxmin: true, //允许全屏最小化
					shade: 0,
					skin: 'layui-layer-molv',
					title: '新增商品基础信息',
					area: ['100%', '100%'],
					content: $("#addBox").html(),
					skin: 'demo-class',
					btn: ["确认新增", "关闭"],
					yes: function(index, layero) {
						//按钮1的回调
						console.log(layero)

						inputisNull(".inputRequired", function() {
							if(imgdata == undefined) {
								layer.msg("请选择图片上传");
							} else {
//								var loading1 = layer.load(0, {
//									shade: false
//								});
								var thisdata = $("#addform").serializeJson(); //商品基础信息
								thisdata.homePhoto = imgdata;
								thisdata.createTime = getnowhour();
								thisdata.createId = '1';
								thisdata.updateId = '1';
								thisdata.updateTime = getnowhour();
								AjaxPostFn('system/commodity/insert', JSON.stringify(thisdata), function(jsonData) {
									if(jsonData.htmlState.status == 200){
										layer.msg("新增商品基础信息成功");
										cMListFn(1, 100, '{"Sorting":"updateTime" }');
									}else{
										layer.msg(jsonData.Error.message);
									}
							
								})

							}
						}); //检查表单是否为空             
					},
					zIndex: layer.zIndex, //重点1
					btn2: function(index, layero) {
						//按钮2的回调
					},
					cancel: function() {
						//右上关闭的回调
					},
					success: function() {
						
						form.render(); //重构form
						$(".upNewimg").val("点击上传");
						
						$(".updataform1").attr("action",AllUrl+"api/qiniu/update");
						$(".updataform1").submit();
						//图片上传form的submit
						$(".upNewimg").click(function() {
								$(".updataform1").submit();
							})
							//图片上传的frame的窗口
						var framFile1 = document.getElementById('framFile1');
						framFile1.onload = function() {
							console.log("最新窗口点击");
							imgdata = framFile1.contentWindow.document.getElementsByTagName("pre")[0].innerHTML;
							imgdata = JSON.parse(imgdata).dataResultObj[0];
							console.log(imgdata);
							if(imgdata == null) {
								$(".upNewimg").val("点击上传");
							} else {
								$(".upNewimg").val("上传成功");
							}
						}
					}
				})
			},
			reload: function() {
				//搜索
				var searchkey = $("#serchselect").val(); //选中的key值
				var demoReload = $("#demoReload").val();
				var needjson = "{ '" + searchkey + "':'" + demoReload + "' }";
				cMListFn(1, 100, needjson);
			},
			returnTable: function() {
				//							搜索处的重置
				cMListFn(1, 100, '{}');
				$("#demoReload").val('')
			},
			yeschoice: function() {
				//选择当前的所选行.
				var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
				var checkStatus = table.checkStatus('cMtable'),
					data = checkStatus.data;
				if(data.length < 1) {
					layer.msg("请选择至少一件商品")
				} else {
					var stockInstr;
					$.each(data, function(idx, obj) {
						var tf = true;
						$.each(parent.$("#stockinTable tbody tr"), function(tridx, trobj) {
							var thisvarcode = parent.$("#stockinTable tbody tr:eq(" + idx + ") td:eq(0)").html()
							if(thisvarcode === obj.barCode) {
								tf = false;
							}
						})
						if(tf) {
							if(GetQueryString("type") == "new") {

							} else {
								stockInstr += '<tr><td onclick="deltr(' + idx + ')"><i class="layui-icon delicon">&#xe640;</i>   </td><td data-stats="0" >等待上传</td><td class="InBarCode" data-cId="' + obj.id + '">' + obj.barCode + '</td>' +
									'<td>' + obj.commodityName + '</td>' +
									'<td>' + obj.homePhoto1 + '</td>' +
									'<td>' + obj.commodityBrand + '</td>' +

									'<td>' + obj.commodityModel + '</td>' +
									'<td>' + obj.commodityOrigin + '</td>' +
									'<td>' + obj.commodityWeigh + '</td>' +
									'<td>' + obj.commodityWeigh + '</td>' +
									'<td>' + obj.commoditySet + '</td>' +

									'<td class="InmerchantNumber">' + obj.merchantNumber + '</td>' +
									'<td><input type="text" class="editTinput theNum" /></td>' +
									'<td><input type="text" class="editTinput averagePrice" /></td>' +
									'<td><input type="text" class="editTinput expireTime" /></td>' +
									'<td><input type="text" class="editTinput comment" /></td>' +
									'</tr>';
							}
						}

					});
					parent.$("#stockinTable tbody").append(stockInstr); //给父级窗口增加指定字符串
					parent.TopimgFn(); //图片点击放大
					parent.layer.close(index); //关闭父级窗口的弹框
				}
			}
		}
		//处理点击之后弹出的选项卡事件
	var tab = parent.tab;
	$('a').off('click').on('click', function() {
		var _that = $(this),
			_data = {
				title: _that.data('title'),
				icon: _that.data('icon'),
				id: _that.data('id'),
				url: _that.data('url')
			};
		tab.tabAdd(_data);
	});
});